package org.zjx.action;

import com.alibaba.fastjson2.JSONObject;
import org.zjx.action.actions.MoveAction;

import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 指令工厂 - 使用多态创建具体指令
 */
public class ActionFactory {
    private static final Map<ActionType, Class<? extends IAction>> ACTION_MAP = new ConcurrentHashMap<>();

    static {
        // 使用ServiceLoader自动发现所有指令提供者
        ServiceLoader<IActionProvider> loader = ServiceLoader.load(IActionProvider.class);
        for (IActionProvider provider : loader) {
            ACTION_MAP.put(provider.getActionType(), provider.getActionClass());
        }

        // 确保核心指令总是可用
        ensureCommand(ActionType.MOVE, MoveAction.class);
    }
    private static void ensureCommand(ActionType type, Class<? extends IAction> actClass) {
        ACTION_MAP.putIfAbsent(type, actClass);
    }

    public static IAction fromJson(JSONObject json) {
        String typeName = json.getString("actionType");
        ActionType type = ActionType.valueOf(typeName);
        Class<? extends IAction> actClass = ACTION_MAP.get(type);

        if (actClass == null) {
            throw new IllegalArgumentException("未注册的指令类型: " + typeName);
        }

        return json.toJavaObject(actClass);
    }

}
